from django import forms
from .models import Supplier, SupplierDocument

class SupplierForm(forms.ModelForm):
    """供应商表单，包含营业执照上传"""
    class Meta:
        model = Supplier
        fields = [
            'name', 'supplier_type', 'credit_code', 'legal_representative',
            'registration_address', 'business_scope', 'contact_person',
            'contact_position', 'phone', 'mobile', 'fax', 'email', 'website',
            'address', 'postal_code', 'bank_name', 'bank_account',
            'bank_address', 'description', 'business_license'
        ]
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入供应商名称'}),
            'supplier_type': forms.Select(attrs={'class': 'form-select'}),
            'credit_code': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入统一社会信用代码'}),
            'legal_representative': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入法定代表人'}),
            'registration_address': forms.Textarea(attrs={'class': 'form-control', 'rows': 3, 'placeholder': '请输入注册地址'}),
            'business_scope': forms.Textarea(attrs={'class': 'form-control', 'rows': 3, 'placeholder': '请输入经营范围'}),
            'contact_person': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入联系人'}),
            'contact_position': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入联系人职务'}),
            'phone': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入联系电话'}),
            'mobile': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入手机号码'}),
            'fax': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入传真'}),
            'email': forms.EmailInput(attrs={'class': 'form-control', 'placeholder': '请输入电子邮箱'}),
            'website': forms.URLInput(attrs={'class': 'form-control', 'placeholder': '请输入公司网址'}),
            'address': forms.Textarea(attrs={'class': 'form-control', 'rows': 3, 'placeholder': '请输入通讯地址'}),
            'postal_code': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入邮政编码'}),
            'bank_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入开户银行'}),
            'bank_account': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入银行账号'}),
            'bank_address': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入开户行地址'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 3, 'placeholder': '请输入供应商描述'}),
            'business_license': forms.FileInput(attrs={'class': 'form-control', 'accept': '.pdf,.jpg,.jpeg,.png'}),
        }

    def clean_business_license(self):
        license_file = self.cleaned_data.get('business_license')
        if license_file:
            # 检查文件大小 (最大5MB)
            if license_file.size > 5 * 1024 * 1024:
                raise forms.ValidationError("营业执照文件大小不能超过5MB")

            # 检查文件类型
            allowed_extensions = ['.pdf', '.jpg', '.jpeg', '.png']
            file_extension = '.' + license_file.name.lower().split('.')[-1]
            if file_extension not in allowed_extensions:
                raise forms.ValidationError("不支持的营业执照文件类型")
        return license_file

class SupplierDocumentForm(forms.ModelForm):
    """供应商资质文件表单"""
    is_permanent = forms.BooleanField(
        required=False,
        label="长期有效",
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'})
    )
    
    class Meta:
        model = SupplierDocument
        fields = ['document_type', 'title', 'file', 'description', 'expiry_date']
        widgets = {
            'document_type': forms.Select(attrs={'class': 'form-select'}),
            'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入文件标题'}),
            'file': forms.FileInput(attrs={'class': 'form-control', 'accept': '.pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 3, 'placeholder': '请输入文件描述'}),
            'expiry_date': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),
        }
    
    def clean(self):
        cleaned_data = super().clean()
        is_permanent = cleaned_data.get('is_permanent')
        expiry_date = cleaned_data.get('expiry_date')
        
        # 如果选择了长期有效，则清空有效期
        if is_permanent:
            cleaned_data['expiry_date'] = None
        elif not expiry_date and not is_permanent:
            # 如果既没有选择长期有效，也没有设置有效期，则不是必须的
            pass
            
        return cleaned_data

    def clean_file(self):
        doc_file = self.cleaned_data.get('file')
        if doc_file:
            # 检查文件大小 (最大10MB)
            if doc_file.size > 10 * 1024 * 1024:
                raise forms.ValidationError("文件大小不能超过10MB")

            # 检查文件类型
            allowed_extensions = ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.jpg', '.jpeg', '.png']
            file_extension = '.' + doc_file.name.lower().split('.')[-1]
            if file_extension not in allowed_extensions:
                raise forms.ValidationError("不支持的文件类型")
        return doc_file
